#include "connect.h"

SOCKET socketfd = 0;

int connectToServer()
{
	struct sockaddr_in addr;

	struct hostent* ptr_hostinfo = gethostbyname(SMTP_SERVER);

	if(ptr_hostinfo==NULL)
		return ERROR_CONNECT_FAIL;

	char** ptr_addrs = ptr_hostinfo->h_addr_list;

	char IP[20];
	memset(&IP, 0, sizeof(IP));
	strcpy(IP, inet_ntoa(*(struct in_addr *)*ptr_addrs));

	memset(&addr, 0, sizeof(addr));

	socketfd = socket(AF_INET, SOCK_STREAM, 0);

	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr(IP);
	addr.sin_port = htons(SMTP_PROT);

	int res = connect(socketfd, (struct sockaddr *)&addr, sizeof(addr));

	if(res == -1)
	{
		releaseSocket(socketfd);
		return ERROR_CONNECT_FAIL;
	}

	char buffer[80];
	int readNum = recv(socketfd, buffer, sizeof(buffer), 0);

	buffer[readNum]='\0';

	return SUCCESS;
}



void releaseSocket(SOCKET socketfd)
{
	closesocket(socketfd);
}

int sendCmdAndGetRsp(const char* cmd)
{
	int count = send(socketfd, cmd, strlen(cmd), 0);

	if(count==-1)
		return -1;

	char buf[50] = {0};

	int res = recv(socketfd, buf, 50, 0);
	if(res==0)
	{
		releaseSocket(socketfd);
		return -1;	
	}

	char* p = strtok(buf, " ");
	int returnCode = atoi(p);

	return returnCode;
}


void releaseResource()
{
	releaseSocket(socketfd);
}